package com.bbx.taxi.client.Util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.api.sdk.model.comm.returns.line.Cities;
import com.bbx.api.sdk.model.comm.returns.line.To_Cities;
import com.bbx.api.sdk.model.official.passanger.Return.LocalCity;
import com.bbx.api.sdk.model.official.passanger.Return.LocalCity.AllCityList;
import com.bbx.api.sdk.model.official.passanger.Return.LocalCity.AllCityList.CityList;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.Bean.City;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.DB.LineDB;
import com.example.loadview.LoadingDialog;

public class ToCity {
	public final static int MSG_SHOW=0;
	public final static int MSG_DISSIOM=1;
	 static LoadingDialog loadDialog;
	public static String split = "市";
	/**本地城市JSON*/
	private final static String fileName = "city.json";
	/**
	 * 获取可去城市
	 */
	public static ArrayList<To_Cities> getToCity(Context context, String name,
			boolean isCity) {
		LineDB db_line = new LineDB(context);
		ArrayList<To_Cities> to_citylist = db_line.readToCityDB(name,isCity);
		if (to_citylist == null) {
			if (name.substring(name.length() - 1).equals(split)) {
				String name_sb = name.substring(0, name.length() - 1);
				to_citylist = db_line.readToCityDB(name_sb,isCity);
			}
			if (to_citylist == null) {
				String name_jia = name + split;
				to_citylist = db_line.readToCityDB(name_jia,isCity);
			}
		}
//		// 不是市内叫车则//移除市内城市
//		if (!isCity&&to_citylist!=null) {
//			for (int i = to_citylist.size() - 1; i >= 0; i--) {
//				if (to_citylist.get(i).getIs_incity() != null) {
//					if (to_citylist.get(i).getIs_incity()
//							.equals(Value.CITY_INCITY)
//							&& to_citylist.get(i).getCn_Name().trim()
//									.equals(name.trim())) {
//						to_citylist.remove(i);
//					}
//				}
//			}
//		}
		return to_citylist;

	}

	/**
	 * 获取线路,name去的地方，to_citylist为根据你之前的地址，可去的地方
	 */
	public static String getLine(ArrayList<To_Cities> to_citylist, String name) {
		String line_id = null;
		if (to_citylist != null)
			for (int i = 0; i < to_citylist.size(); i++) {
				if (name.equals(to_citylist.get(i).getCn_Name())) {
					line_id = to_citylist.get(i).getLine_id();
					break;
				}
				if (line_id == null) {
					if (name.substring(name.length() - 1).equals(split)) {
						String name_sb = name.substring(0, name.length() - 1);
						if (name_sb.equals(to_citylist.get(i).getCn_Name())) {
							line_id = to_citylist.get(i).getLine_id();
							break;
						}
					}
					if (line_id == null) {
						String name_jia = name + split;
						if (name_jia.equals(to_citylist.get(i).getCn_Name())) {
							line_id = to_citylist.get(i).getLine_id();
							break;
						}
					}
				}
			}
		return line_id;
	}

	/**
	 * 判断该地址是否是具体信息。
	 */
	public static String getCityDetail(Context context, String address) {
		LineDB db_line = new LineDB(context);
		List<Cities> citieslist = new ArrayList<Cities>();
		citieslist.addAll(db_line.readAllDB());
		for (int i = 0; i < citieslist.size(); i++) {
			String name = citieslist.get(i).getCn_Name();
			String detail = citieslist.get(i).getIs_detail();
			if (address.startsWith(name)) {
				if (detail.equals(Value.CITY_DETAIL)) {
					return name;
				}
			}
			ArrayList<To_Cities> to_citylist = ToCity.getToCity(context, name,
					false);
			if (to_citylist != null) {
				for (int j = 0; j < to_citylist.size(); j++) {
					String to_name = to_citylist.get(j).getCn_Name();
					String to_detail = to_citylist.get(j).getIs_detail();
					if (address.startsWith(to_name)) {
						if (to_detail.equals(Value.CITY_DETAIL)) {
							return to_name;
						}
					}
				}
			}
		}
		return null;

	}

	/**
	 * 设置全部城市列表
	 */
	public static void setCityList(final Context context) {
		final LineDB db_line = new LineDB(context);
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<City> cityList = new ArrayList<City>();
				MyApplication.isCityListComplite = false;
				cityList.clear();
				List<Cities> citieslist = new ArrayList<Cities>();
				citieslist.addAll(db_line.readAllDB());
				if (citieslist != null && !citieslist.isEmpty()) {
					for (int i = 0; i < citieslist.size(); i++) {
						boolean isAdd=true;//判断是否添加,市内都不加
						ArrayList<To_Cities> to_citylist = getToCity(context, citieslist.get(i).getCn_Name(),
								(citieslist.get(i).getIs_city()!=null&&citieslist.get(i).getIs_city().equals(Value.CITY_INCITY)));
						if(to_citylist!=null&&to_citylist.size()<=1){ 
							//只有1个的时候，不能为市内，却不能为隐藏
							if(to_citylist.size()==1&&to_citylist.get(0).getIs_incity().equals(Value.CITY_INCITY)){
								isAdd=false;
							}
							else if(to_citylist.size()==1&&to_citylist.get(0).getIsShow().equals(Value.CITY_NOSHOW)){
								isAdd=false;
							}
							else if(to_citylist.size()==0){
								isAdd=false;
							}
						}else{
							//判断所有的子类,如果有一项没有隐藏，则显示
							if(to_citylist!=null){
							for(int z=0;z<to_citylist.size();z++){
								if(to_citylist.get(z).getIsShow().equals(Value.CITY_SHOW)){
										isAdd=true;
										break;
									}
								else if(z==to_citylist.size()-1){
									isAdd=false;
								}
								}
							}
						}
						if (citieslist.get(i).getIs_city() != null
								&& citieslist.get(i).getIs_city()
										.equals(Value.CITY_INCITY)) {
							isAdd = false;
						}
						for(int z=0;z<cityList.size();z++){
							City city =cityList.get(z);
							if(city.getCity().equals(citieslist.get(i).getCn_Name())){
									isAdd=false;
									break;
								}
							}
						if(isAdd){
						City city = new City();
						city.setCity(citieslist.get(i).getCn_Name());
						city.setProvince("");// 设置省份
						city.setNumber("");//
						city.setAllPY(citieslist.get(i).getName());
						city.setAllFristPY(citieslist.get(i).getAbbr());
						if(citieslist.get(i).getName()!=null)
						city.setFirstPY(Cn2Spell.getInstance()
								.onCn2Spell(citieslist.get(i).getName())
								.charAt(0)
								+ "");
						city.setIs_new(citieslist.get(i).getIs_new());
						city.setIs_detail(citieslist.get(i).getIs_detail());
						cityList.add(city);
						}
					}
					MyApplication mApplication = MyApplication.getInstance();
					mApplication.onPrepareCity(cityList);
				}
			}
		}).start();
	}
	static List<City> allcity = new ArrayList<City>();
	/**
	 * 设置本地数据城市
	 */
	public static void setLocalCityList(final Context context) {
		new AsyncTask<Void, Void, Void>(){
            
			@Override
			protected void onPreExecute() {
				loadDialog=new LoadingDialog(context);
				allcity.clear();
				mHandler.sendEmptyMessage(MSG_SHOW);
				super.onPreExecute();
			}

			@Override
			protected Void doInBackground(Void... params) {
				String jsonStr = AppJsonFileReader.getJson(context,fileName); 	
					LocalCity mLocalCity = (LocalCity) new JsonBuild().getData(LocalCity.class,
							jsonStr);
					ArrayList<AllCityList> allcityList=mLocalCity.getAllCityList();
					for(int i=0;i<allcityList.size();i++){
						ArrayList<CityList> cityList=allcityList.get(i).getCityList();
						//有子城市
						if(cityList!=null&&cityList.size()>0){
							for(int num=0;num<cityList.size();num++){
								String name=cityList.get(num).getName();
								String province=allcityList.get(i).getName();
								String allpy=cityList.get(num).getPinyin();
								String AllFristPY=cityList.get(num).getShortPinyin();
								String firstPY=AllFristPY.length()>=1?AllFristPY.charAt(0)+"":"";
								allcity.add(getCityInfo(name, province, allpy, AllFristPY, firstPY));
							}
						}
						//没有子城市，则是直辖市那些
						else{
							String name=allcityList.get(i).getName();
							String province=allcityList.get(i).getName();
							String allpy=allcityList.get(i).getPinyin();
							String AllFristPY=allcityList.get(i).getShortPinyin();
							String firstPY=AllFristPY.length()>=1?AllFristPY.charAt(0)+"":"";
							allcity.add(getCityInfo(name, province, allpy, AllFristPY, firstPY));
						}
						
					}
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				MyApplication mApplication = MyApplication.getInstance();
				mApplication.onPrepareCity(allcity);
				mHandler.sendEmptyMessage(MSG_DISSIOM);
				super.onPostExecute(result);
			}
			
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

		
	}
	/**设置城市信息
	 * @param cityList，需要添加到
	 * @param cityname，城市名字
	 * @param province，城市省份
	 * @param allpy，城市全拼
	 * @param AllFristPY，城市的缩写，也就是各个字的首拼
	 * @param firstPY，城市的首拼
	 */
	public static City getCityInfo(String cityname,String province,String allpy,String AllFristPY,String firstPY){
		City city = new City();
		city.setCity(cityname);
		city.setProvince(province);// 设置省份
		city.setNumber("");//
		city.setAllPY(allpy);
		city.setAllFristPY(AllFristPY);
		city.setFirstPY(firstPY);
		return city;
	}
	/**
	 * 设置可去的城市列表
	 */
	public static ArrayList<To_Cities> setToCityList(final Context context,
			final String cityname) {
		List<City> cityList = new ArrayList<City>();
		MyApplication.isCityListComplite = false;
		cityList.clear();
		ArrayList<To_Cities> to_citylist = ToCity.getToCity(context, cityname,
				false);
		ArrayList<To_Cities> return_to_citylist = new ArrayList<To_Cities>();
		if (to_citylist != null && !to_citylist.isEmpty()) {
			for (int i = 0; i < to_citylist.size(); i++) {
				if (to_citylist.get(i).getIs_incity() != null) {
					if (to_citylist.get(i).getIs_incity()
							.equals(Value.CITY_NOINCITY)&&to_citylist.get(i).getIsShow().equals(Value.CITY_SHOW)) {
						return_to_citylist.add(to_citylist.get(i));
						City city = new City();
						city.setCity(to_citylist.get(i).getCn_Name());
						city.setProvince("");// 设置省份
						city.setNumber("");//
						city.setAllPY(to_citylist.get(i).getName());
						city.setAllFristPY(Cn2Spell.getInstance().onCn2Spell(
								to_citylist.get(i).getCn_Name()));
						if(to_citylist.get(i).getName()!=null)
						city.setFirstPY(Cn2Spell.getInstance()
								.onCn2Spell(to_citylist.get(i).getName())
								.charAt(0)
								+ "");
						city.setIs_new(to_citylist.get(i).getIs_new());
						city.setIs_detail(to_citylist.get(i).getIs_detail());
						cityList.add(city);
					}
				} else {
					return_to_citylist.add(to_citylist.get(i));
					City city = new City();
					city.setCity(to_citylist.get(i).getCn_Name());
					city.setProvince("");// 设置省份
					city.setNumber("");//
					city.setAllPY(to_citylist.get(i).getName());
					city.setAllFristPY(Cn2Spell.getInstance().onCn2Spell(
							to_citylist.get(i).getCn_Name()));
					city.setFirstPY(Cn2Spell.getInstance()
							.onCn2Spell(to_citylist.get(i).getCn_Name())
							.charAt(0)
							+ "");
					city.setIs_new(to_citylist.get(i).getIs_new());
					city.setIs_detail(to_citylist.get(i).getIs_detail());
					cityList.add(city);
				}
			}
			MyApplication mApplication = MyApplication.getInstance();
			mApplication.onPrepareCity(cityList);
		}
		return return_to_citylist;
	}
    
	/**
	 * 设置市内用车城市列表
	 */
	public static void setInCityList(Context context) {
		final String str_incity_cn = SharedPreUtil.getStringValue(context,
				SharedPreEncryptUtil.list_incity_cn, "");

		new Thread(new Runnable() {
			@Override
			public void run() {
				List<String> list_incity_cn = null;
				if (!str_incity_cn.equals("") && str_incity_cn != null) {
					list_incity_cn = Arrays.asList(str_incity_cn
							.replace("[", "").replace("]", "").trim()
							.split(","));
				}
				List<City> cityList = new ArrayList<City>();
				MyApplication.isCityListComplite = false;
				cityList.clear();
				if (list_incity_cn != null && list_incity_cn.size() > 0) {
					for (int i = 0; i < list_incity_cn.size(); i++) {
						City city = new City();
						city.setCity(list_incity_cn.get(i));
						city.setProvince("");// 设置省份
						city.setNumber("");//
						city.setAllPY(Cn2Spell.getInstance().onCn2Spell(
								list_incity_cn.get(i)));
						city.setAllFristPY(Cn2Spell.getInstance().onCn2Spell(
								list_incity_cn.get(i)));
						city.setFirstPY(Cn2Spell.getInstance()
								.onCn2Spell(list_incity_cn.get(i)).charAt(0)
								+ "");
						// city.setIs_new(citieslist.get(i).getIs_new());
						// city.setIs_detail(citieslist.get(i).getIs_detail());
						cityList.add(city);
					}
					MyApplication mApplication = MyApplication.getInstance();
					mApplication.onPrepareCity(cityList);
				}
			}
		}).start();
	}

	/**
	 * 根据地址获取城市
	 */
	public static String getCity(String address) {
		String city;
		if (address.contains(" ")) {
			city = address.substring(0, address.indexOf(" "));
		} else if (address.contains("\t")) {
			city = address.substring(0, address.indexOf("\t"));
		} else if (address.contains("-")) {
			city = address.substring(0, address.indexOf("-"));
		} else {
			city = address;
		}
		return city;
	}
	/**
	 * 获取城市的名字，去掉市。
	 */
	public static String getCityName(String city){
		if(city.length()>0&&city.substring(city.length() - 1).equals(ToCity.split)){
			city=city.substring(0,city.length()-1);
    	}
		return city;
	}
	//mContext.getMainLooper()防止在线程调用会闪退
 	public static Handler mHandler=new Handler(MyApplication.getInstance().getApplicationContext().getMainLooper()){
		public void handleMessage(android.os.Message msg) {
			 super.handleMessage(msg);
			switch(msg.what){
			case MSG_SHOW:
				if(loadDialog!=null&&!loadDialog.isShowing()){
					loadDialog.dismiss();
				}
				break;
			case MSG_DISSIOM:
				if(loadDialog!=null){
					loadDialog.dismiss();
				}
				break;
			}
		};
	};
}
